<template>
  <div>
    <el-form
      ref="form"
      v-model="form"
      :model="form"
      label-width="100px"
      class="demo-ruleForm"
      :rules="rules"
    >
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" placeholder="请选择部门负责人">
          <el-option
            v-for="item in employee"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" type="textarea" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="cacel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  getEmployeeSimple,
  addDepartments,
  getDepartDetail,
  updateDepartments
} from '@/api/departments'

export default {
  name: 'DeptDialog',

  props: {
    chilerenId: {
      type: [Number, String],
      required: true
    },
    // 编辑状态
    isedit: {
      type: Boolean,
      required: true
    },
    // 接收父亲传递过来的精简数据
    originList: {
      type: Array,
      required: true
    }
  },

  data() {
    // 验证编码:编码在整个部门都不能重复
    const validCode = (rule, value, callback) => {
      let existCodeList = this.originList.map(item => item.code)
      // 先确定是编辑的话,不能弹出编码重复这个消息
      if (this.isedit) {
        existCodeList = this.originList.filter(item => item.id !== this.chilerenId).map(item => item.code)
      }
      // 验证编码是否存在,不存在就放行
      existCodeList.includes(value) ? callback(new Error(`编码 ${value} 已存在`)) : callback()
    }

    // 验证部门名称,不能重复
    // 新增的公式:通过父亲id===子级的pid对比,查找新增项的同级部门

    const validName = (rule, value, callback) => {
      let exitvalidName = this.originList.filter(item => item.pid === this.chilerenId).map(item => item.name)

      // 先找兄弟节点,判断是否是编辑
      if (this.isedit) {
        const obj = this.originList.find(item => item.id === this.chilerenId)
        // 获取到本身以后,才能获取pid
        const pid = obj.pid

        // 根据pid才能获取到同级,找到同级的时候将自己排除掉
        exitvalidName = this.originList
          .filter(item => item.pid === pid && item.pid !== this.chilerenId)
          .map(item => item.name)
      }
      exitvalidName.includes(value) ? callback(new Error(`部门 ${value} 已经存在`)) : callback()
    }
    return {
      form: {
        code: '', // 部门编码，同级部门不可重复
        introduce: '', // 介绍
        manager: '', // 负责人名称
        name: '' // 部门名称
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { trigger: 'blur', validator: validCode }

        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      },
      employee: [] // 部门负责人
    }
  },
  created() {
    // 调用负责人方法
    this.getEmployeeSimpleFn()
    // 获取部门详情
    this.getDepartDetail()
  },
  methods: {
    // 编辑子部门
    async editSondepents() {
      const res = await updateDepartments(this.form)
      console.log(res)
      this.$emit('closeDialog')
      this.$message.success(res.message)
    },
    // 获取部门详情
    async getDepartDetail() {
      if (this.isedit) {
        // 编辑的话
        const res = await getDepartDetail(this.chilerenId)
        console.log(res)
        this.form = res.data
      }
    },
    // 调用负责人方法
    async getEmployeeSimpleFn() {
      const res = await getEmployeeSimple()
      console.log(res)
      this.employee = res.data
    },
    // 确定按钮+兜底验证
    async submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) return
        this.isedit ? this.editSondepents() : this.addDepartmentsFn()
      })
    },
    // 添加子部门
    async addDepartmentsFn() {
      const res = await addDepartments({ ...this.form, pid: this.parentId })
      console.log(res)
      //   this.form = res.data
      this.$emit('closeDialog')
      this.$message.success(res.message)
    },
    // 取消按钮
    cacel() {
      this.$emit('shiftDialog')
    }
  }
}
</script>

<style>
.el-select {
  width: 100%;
}
.el-form demo-ruleForm {
  padding: 0 60px 0 20px;
}
</style>
